from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import AllowAny, IsAuthenticated, IsAdminUser
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.authentication import JWTAuthentication
from django.contrib.auth import authenticate
from .models import User, Role
from django.db.models import Count, Q
from rest_framework.pagination import PageNumberPagination
import datetime
from django.utils import timezone
from django.db import transaction

# Create your views here.

@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
    try:
        data = request.data
        required_fields = ['username', 'password', 'name', 'email', 'gender']
        
        # 检查必填字段
        for field in required_fields:
            if not data.get(field):
                return Response({
                    'message': f'请填写{field}'
                }, status=status.HTTP_400_BAD_REQUEST)
        
        # 验证性别字段
        if data['gender'] not in ['M', 'F']:
            return Response({
                'message': '性别只能是男或女'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        # 验证用户名是否已存在
        if User.objects.filter(username=data['username']).exists():
            return Response({
                'message': '用户名已存在'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        # 验证邮箱是否已存在
        if User.objects.filter(email=data['email']).exists():
            return Response({
                'message': '邮箱已被使用'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 获取客户端IP
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        
        # 创建用户
        user = User.objects.create_user(
            username=data['username'],
            password=data['password'],
            name=data['name'],
            email=data['email'],
            gender=data['gender'],
            ip_address=ip
        )
        
        return Response({
            'message': '注册成功',
            'user': {
                'id': user.id,
                'name': user.name,
                'username': user.username,
                'email': user.email,
                'role': user.get_role_display(),
                'is_active': user.is_active
            }
        }, status=status.HTTP_200_OK)
    except Exception as e:
        return Response({
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
    try:
        username = request.data.get('username')
        password = request.data.get('password')
        
        user = authenticate(username=username, password=password)
        
        if user is not None:
            # 更新登录信息
            user.login_count += 1
            user.last_login = timezone.now()
            user.save()
            
            # 生成Token
            refresh = RefreshToken.for_user(user)
            
            return Response({
                'message': '登录成功',
                'token': {
                    'access': str(refresh.access_token),
                    'refresh': str(refresh)
                },
                'user': {
                    'id': user.id,
                    'name': user.name,
                    'username': user.username,
                    'email': user.email,
                    'role': user.get_role_display(),
                    'is_active': user.is_active,
                    'is_admin': user.is_admin,
                    'is_staff': user.is_staff,
                    'is_superuser': user.is_superuser,
                    'login_count': user.login_count
                }
            })
        else:
            return Response({
                'message': '用户名或密码错误'
            }, status=status.HTTP_401_UNAUTHORIZED)
    except Exception as e:
        return Response({
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
@permission_classes([AllowAny])
def logout(request):
    try:
        refresh_token = request.data.get('refresh_token')
        token = RefreshToken(refresh_token)
        token.blacklist()
        return Response({
            'message': '退出成功'
        })
    except Exception as e:
        return Response({
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_users(request):
    """获取用户列表"""
    try:
        # 创建分页器
        paginator = PageNumberPagination()
        paginator.page_size = 10
        
        # 获取查询参数
        search = request.GET.get('search', '')
        status = request.GET.get('status', '')
        
        # 构建查询
        users = User.objects.all()
        
        if search:
            users = users.filter(
                Q(username__icontains=search) |
                Q(name__icontains=search) |
                Q(email__icontains=search)
            )
            
        if status:
            users = users.filter(is_active=status == 'active')
            
        # 执行分页
        page = paginator.paginate_queryset(users, request)
        
        # 准备响应数据
        data = []
        for user in page:
            user_data = {
                'id': user.id,
                'username': user.username,
                'name': user.name,
                'email': user.email,
                'gender': user.get_gender_display(),
                'phone': user.phone,
                'is_active': user.is_active,
                'is_admin': user.is_admin,
                'is_superuser': user.is_superuser,
                'role': user.get_role_display(),
                'login_count': user.login_count,
                'last_login': user.last_login,
                'created_at': user.created_at
            }
            data.append(user_data)
            
        return Response({
            'status': 'success',
            'data': data,
            'total': users.count(),
            'page_size': paginator.page_size,
            'current_page': paginator.page.number
        })
    except Exception as e:
        return Response({
            'status': 'error',
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_user_detail(request, user_id):
    """获取用户详情"""
    try:
        user = User.objects.get(id=user_id)
        data = {
            'id': user.id,
            'username': user.username,
            'name': user.name,
            'email': user.email,
            'gender': user.get_gender_display(),
            'phone': user.phone,
            'is_active': user.is_active,
            'is_admin': user.is_admin,
            'is_superuser': user.is_superuser,
            'role': user.get_role_display(),
            'login_count': user.login_count,
            'last_login': user.last_login,
            'created_at': user.created_at
        }
        return Response({
            'status': 'success',
            'data': data
        })
    except User.DoesNotExist:
        return Response({
            'status': 'error',
            'message': '用户不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'status': 'error',
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['PUT'])
@permission_classes([IsAuthenticated])
def update_user(request, user_id):
    """更新用户信息"""
    try:
        user = User.objects.get(id=user_id)
        
        # 只允许管理员或用户本人修改信息
        if not (request.user.is_admin or request.user.id == user_id):
            return Response({
                'status': 'error',
                'message': '没有权限执行此操作'
            }, status=status.HTTP_403_FORBIDDEN)
            
        # 更新基本信息
        if 'name' in request.data:
            user.name = request.data['name']
        if 'email' in request.data:
            user.email = request.data['email']
        if 'gender' in request.data:
            user.gender = request.data['gender']
        if 'phone' in request.data:
            user.phone = request.data['phone']
            
        # 只有管理员可以更新这些字段
        if request.user.is_admin:
            if 'is_active' in request.data:
                user.is_active = request.data['is_active']
            if 'is_admin' in request.data:
                user.is_admin = request.data['is_admin']
            if 'role' in request.data:
                user.role_id = request.data['role']
                
        # 如果提供了新密码
        if 'password' in request.data:
            user.set_password(request.data['password'])
            
        user.save()
        return Response({
            'status': 'success',
            'message': '用户信息更新成功'
        })
    except User.DoesNotExist:
        return Response({
            'status': 'error',
            'message': '用户不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'status': 'error',
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
def delete_user(request, user_id):
    """删除用户"""
    try:
        # 只允许管理员删除用户
        if not request.user.is_admin:
            return Response({
                'status': 'error',
                'message': '没有权限执行此操作'
            }, status=status.HTTP_403_FORBIDDEN)
            
        user = User.objects.get(id=user_id)
        
        # 不允许删除超级管理员
        if user.is_superuser:
            return Response({
                'status': 'error',
                'message': '不能删除超级管理员'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        user.delete()
        return Response({
            'status': 'success',
            'message': '用户删除成功'
        })
    except User.DoesNotExist:
        return Response({
            'status': 'error',
            'message': '用户不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'status': 'error',
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def toggle_user_status(request, user_id):
    """切换用户状态（启用/禁用）"""
    try:
        # 只允许管理员操作
        if not request.user.is_admin:
            return Response({
                'status': 'error',
                'message': '没有权限执行此操作'
            }, status=status.HTTP_403_FORBIDDEN)
            
        user = User.objects.get(id=user_id)
        
        # 不允许禁用超级管理员
        if user.is_superuser:
            return Response({
                'status': 'error',
                'message': '不能禁用超级管理员'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        user.is_active = not user.is_active
        user.save()
        
        return Response({
            'status': 'success',
            'message': f'用户已{"启用" if user.is_active else "禁用"}'
        })
    except User.DoesNotExist:
        return Response({
            'status': 'error',
            'message': '用户不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'status': 'error',
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

# 角色管理相关视图
@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
def get_roles(request):
    """获取所有角色列表"""
    try:
        roles = Role.objects.all()
        data = [{
            'id': role.id,
            'name': role.name,
            'code': role.code,
            'description': role.description,
            'permissions': role.permissions,
            'is_system': role.is_system,
            'created_at': role.created_at,
            'updated_at': role.updated_at
        } for role in roles]
        
        return Response({
            'status': 'success',
            'data': data
        })
    except Exception as e:
        return Response({
            'status': 'error',
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAdminUser])
def create_role(request):
    """创建新角色"""
    try:
        # 验证必填字段
        required_fields = ['name', 'code']
        for field in required_fields:
            if not request.data.get(field):
                return Response({
                    'status': 'error',
                    'message': f'请填写{field}'
                }, status=status.HTTP_400_BAD_REQUEST)
        
        # 验证角色名称是否已存在
        if Role.objects.filter(name=request.data.get('name')).exists():
            return Response({
                'status': 'error',
                'message': '角色名称已存在'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        # 验证角色代码是否已存在
        if Role.objects.filter(code=request.data.get('code')).exists():
            return Response({
                'status': 'error',
                'message': '角色代码已存在'
            }, status=status.HTTP_400_BAD_REQUEST)

        with transaction.atomic():
            role = Role.objects.create(
                name=request.data.get('name'),
                code=request.data.get('code'),
                description=request.data.get('description', ''),
                permissions=request.data.get('permissions', {}),
                is_system=False  # 手动创建的角色默认不是系统角色
            )
            
        return Response({
            'status': 'success',
            'message': '角色创建成功',
            'data': {
                'id': role.id,
                'name': role.name,
                'code': role.code,
                'description': role.description,
                'permissions': role.permissions
            }
        })
    except Exception as e:
        return Response({
            'status': 'error',
            'message': f'角色创建失败: {str(e)}'
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['PUT'])
@permission_classes([IsAdminUser])
def update_role(request, role_id):
    """更新角色信息"""
    try:
        role = Role.objects.get(id=role_id)
        if role.is_system:
            return Response({
                'status': 'error',
                'message': '系统角色不能修改'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        with transaction.atomic():
            if 'name' in request.data:
                role.name = request.data['name']
            if 'code' in request.data:
                role.code = request.data['code']
            if 'description' in request.data:
                role.description = request.data['description']
            if 'permissions' in request.data:
                role.permissions = request.data['permissions']
            role.save()
            
        return Response({
            'status': 'success',
            'message': '角色更新成功',
            'data': {
                'id': role.id,
                'name': role.name,
                'code': role.code
            }
        })
    except Role.DoesNotExist:
        return Response({
            'status': 'error',
            'message': '角色不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'status': 'error',
            'message': f'角色更新失败: {str(e)}'
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['DELETE'])
@permission_classes([IsAdminUser])
def delete_role(request, role_id):
    """删除角色"""
    try:
        role = Role.objects.get(id=role_id)
        if role.is_system:
            return Response({
                'status': 'error',
                'message': '系统角色不能删除'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        # 检查是否有用户正在使用该角色
        if role.user_set.exists():
            return Response({
                'status': 'error',
                'message': '该角色下存在用户，无法删除'
            }, status=status.HTTP_400_BAD_REQUEST)
            
        role.delete()
        return Response({
            'status': 'success',
            'message': '角色删除成功'
        })
    except Role.DoesNotExist:
        return Response({
            'status': 'error',
            'message': '角色不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'status': 'error',
            'message': f'角色删除失败: {str(e)}'
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@authentication_classes([JWTAuthentication])
@permission_classes([IsAuthenticated])
def get_role_detail(request, role_id):
    """获取角色详情"""
    try:
        role = Role.objects.get(id=role_id)
        data = {
            'id': role.id,
            'name': role.name,
            'code': role.code,
            'description': role.description,
            'permissions': role.permissions,
            'is_system': role.is_system,
            'created_at': role.created_at,
            'updated_at': role.updated_at,
            'user_count': role.user_set.count()
        }
        return Response({
            'status': 'success',
            'data': data
        })
    except Role.DoesNotExist:
        return Response({
            'status': 'error',
            'message': '角色不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'status': 'error',
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_current_user_detail(request):
    """获取当前登录用户的详情"""
    try:
        user = request.user
        data = {
            'id': user.id,
            'username': user.username,
            'name': user.name,
            'email': user.email,
            'gender': user.get_gender_display(),
            'phone': user.phone,
            'is_active': user.is_active,
            'is_admin': user.is_admin,
            'is_superuser': user.is_superuser,
            'role': user.get_role_display(),
            'login_count': user.login_count,
            'last_login': user.last_login,
            'created_at': user.created_at,
            'updated_at': user.updated_at,
            'ip_address': user.ip_address
        }
        return Response({
            'status': 'success',
            'data': data
        })
    except Exception as e:
        return Response({
            'status': 'error',
            'message': str(e)
        }, status=status.HTTP_400_BAD_REQUEST)
